package com.patrol.logisticsmanage.ui.login;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.android.material.textfield.TextInputEditText;
import com.patrol.logisticsmanage.R;
import com.patrol.logisticsmanage.R2;
import com.patrol.logisticsmanage.net.AppConfig;
import com.patrol.logisticsmanage.net.BaseObserver;
import com.patrol.logisticsmanage.net.BaseReponse;
import com.patrol.logisticsmanage.net.BaseRequest;
import com.patrol.logisticsmanage.net.NetWorkUtils;
import com.patrol.logisticsmanage.ui.base.BaseActivity;
import com.patrol.logisticsmanage.ui.canteen.utils.ToastUtils;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

@Route(path = "/app/login")
public class LoginActivity extends BaseActivity {

//    @BindView(R2.id.tv_forget_password)
//    AppCompatTextView tvForgetPassword;
    @BindView(R2.id.tv_login)
    TextView tvLogin;
//    @BindView(R2.id.tv_login_register)
//    TextView tvLoginRegister;
    @BindView(R2.id.et_login_account)
    TextInputEditText etLoginAccount;
    @BindView(R2.id.iv_login_account_clear)
    ImageView ivLoginAccountClear;
    @BindView(R2.id.et_login_password)
    TextInputEditText etLoginPassword;
    @BindView(R2.id.iv_login_password_see)
    ImageView ivLoginPasswordSee;
    @BindView(R2.id.iv_login_password_clear)
    ImageView ivLoginPasswordClear;
    @BindView(R.id.img_back)
    ImageView imgBack;

    SharedPreferences preferences;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        preferences = getSharedPreferences("info",MODE_PRIVATE);
        ButterKnife.bind(this);
//        if (!TextUtils.isEmpty(AppConfig.getString("account"))) {
//            etLoginAccount.setText(AppConfig.getString("account"));
//            etLoginAccount.setSelection(AppConfig.getString("account").length());
//        }
        etLoginAccount.setText(preferences.getString("account",""));
        etLoginPassword.setText(preferences.getString("password",""));

//        boolean isError = AppConfig.getBoolean("isError");
//        if(!isError) {
//            if (!TextUtils.isEmpty(AppConfig.getString("token"))) {
//                ARouter.getInstance().build("/app/main").navigation();
//                AppConfig.putBoolean("isError", false);
//                finish();
//            }
//        }
        tvLogin.performClick();
    }


    @OnClick({R2.id.tv_login, R2.id.iv_login_account_clear, R2.id.iv_login_password_see, R2.id.iv_login_password_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_login:
                String userName = etLoginAccount.getText().toString().trim();
                String password = etLoginPassword.getText().toString().trim();
//                if (password.length() < 6 || password.length() > 15) {
//                    ToastUtils.showToast("密码格式不正确");
//                    return;
//                }
                checkInputStatus(userName, password);
                break;
//            case R.id.tv_login_register:
//                ARouter.getInstance().build("/app/RegisterActivity").withString("from", "register").navigation();
//                break;
//            case R.id.tv_forget_password:
//                ARouter.getInstance().build("/app/RegisterActivity").withString("from", "forgetPwd").navigation();
//                break;
            case R.id.iv_login_account_clear:
                etLoginAccount.setText("");
                break;
            case R.id.iv_login_password_see:
                etLoginPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                break;
            case R.id.iv_login_password_clear:
                etLoginPassword.setText("");
                break;
            default:
                break;
        }
    }

    private void checkInputStatus(String userName, String password) {
        if (TextUtils.isEmpty(userName)) {
            ToastUtils.centerToastWhite(this, "请输入账号");
        } else if (TextUtils.isEmpty(password)) {
            ToastUtils.centerToastWhite(this, "请输入密码");
        } else {
            boolean connect = NetWorkUtils.isConnect(this);
            if (connect) {

                //登录
                LoginInfo loginInfo = LoginInfo.builder().setUsername(userName).setPassword(password).build();
                BaseRequest.getInstance().getApiServise().applogin(userName,password,"http://172.18.51.82/houqin")
//                BaseRequest.getInstance().getApiServise().login(loginInfo)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<Map>(this) {
                            @Override
                            public void onSuccess(BaseReponse<Map> loginMap) {
                                editor = preferences.edit();
                                editor.putString("account",userName);
                                editor.putString("password",password);
                                editor.commit();
                                Map userInfo = (Map) loginMap.getResults().get("userInfo");
                                String token = (String) loginMap.getResults().get("token");
                                AppConfig.putString("token",token);
                                String userId = (String) userInfo.get("id");
                                String userName = (String) userInfo.get("username");
                                String realname = (String) userInfo.get("realname");
                                String telephone = (String) userInfo.get("phone");
                                AppConfig.putString("token",token);
                                AppConfig.putString("userId",userId);
                                AppConfig.putString("userName",userName);
                                AppConfig.putString("realname",realname);
                                AppConfig.putString("phone",telephone);
                                ToastUtils.showToast("登录成功");
                                BaseRequest.getInstance().reset(token);
                                AppConfig.putBoolean("isError",false);
                                JPushInterface.setAlias(mContext, 2010, userName);
                                ARouter.getInstance().build("/app/main").navigation();
                                finish();
                            }

                            @Override
                            public void onCodeError(BaseReponse tBaseReponse) {
                                ToastUtils.centerToastWhite(mContext,tBaseReponse.getMessage());
                            }

                            @Override
                            public void onFailure(Throwable e, boolean netWork) throws Exception {
                                ToastUtils.centerToastWhite(mContext,e.getMessage());
                            }
                        });

            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @OnClick(R.id.img_back)
    public void onViewClicked() {
        finish();
    }
}